package com.eques.demo.anim

import android.annotation.SuppressLint
import android.graphics.Color
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.TextView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.eques.base.BaseActivity
import com.eques.bean.Alarm
import com.eques.bean.AnimalAlarmInfo
import com.eques.demo.R
import com.eques.demo.adapter.AnimalAdapter
import com.eques.impl.OnClickListenerImpl
import com.eques.util.Config
import okhttp3.OkHttpClient
import okhttp3.Request
import org.json.JSONObject
import java.io.IOException
import java.util.Objects
import java.util.concurrent.Executors

class AnimalAlarmActivity : BaseActivity() , OnClickListenerImpl {
    private var TAG= AnimalAlarmActivity::class.java.simpleName
    private var lockId=""

    private var rlMainHeadParent: ConstraintLayout? = null
    private var tvMainLeftTopHint: TextView? = null
    private var tvMainTitleHint: TextView? = null
    var lists: MutableList<AnimalAlarmInfo>? = null
    var listData:MutableList<Alarm>?=null
    private var rec_data: RecyclerView?=null
    private var animalPlanAdapter: AnimalAdapter? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_alarm)
        initView()
        initRecView()
        initData()
    }

    private fun initRecView(){
        rec_data=findViewById(R.id.rec_data)
        val linearLayoutManager= LinearLayoutManager(this)
        rec_data?.layoutManager=linearLayoutManager
        lists=mutableListOf()
        animalPlanAdapter= AnimalAdapter(this,lists as List<Objects>,2)
        animalPlanAdapter!!.setOnItemClickListener(this)
        rec_data?.adapter=animalPlanAdapter
    }

    /**
     * 初始化头部标题栏
     */
    private fun initTitleView() {
        tvMainLeftTopHint!!.visibility = View.VISIBLE
        tvMainLeftTopHint?.setCompoundDrawablesWithIntrinsicBounds(
            resources.getDrawable(R.mipmap.ic_invitation_menu),
            null,
            null,
            null
        )
        tvMainLeftTopHint?.setOnClickListener {
                finish()
        }
        rlMainHeadParent!!.setBackgroundColor(Color.WHITE)
        tvMainTitleHint?.visibility = View.VISIBLE
        tvMainTitleHint?.text = getString(R.string.xm_dev_settings)
        tvMainTitleHint?.setTextColor(resources.getColor(R.color.common_color_333333))
    }

    override fun initView() {
        tvMainLeftTopHint = findViewById(R.id.tv_main_left_top_hint)
        tvMainTitleHint = findViewById(R.id.tv_main_title_hint)
        rlMainHeadParent = findViewById(R.id.rl_main_head_parent)
        initTitleView()
    }

    override fun initData() {
        listData= mutableListOf()
        lockId= intent.getStringExtra(Config.BID).toString()
        Executors.newSingleThreadExecutor().submit {
            getAlarmMsg()
        }
    }

    private fun getAlarmMsg() {
        var subIp = preference.getString(Config.SUB_ADDRESS)
        val token = preference.getString(Config.EQUES_USER_TOKEN)
        var uid = preference.getString(Config.EQUES_USER_UID)
        val url = Config.getE1ProOpenLockAlarmListUrl(
            subIp!!,
            uid!!,
            token!!,
            lockId,
           "",
            "",
            "0",
            "1000"
        )
        Log.e(TAG, "....url..$url")
        val client = OkHttpClient()
        val request = Request.Builder()
            .url(url!!)
            .build()
        client.newCall(request).execute().use { response ->
            if (!response.isSuccessful) throw IOException("Unexpected code $response")
            val jsonObject = response.body?.string()?.let { JSONObject(it) }
            try {
                val code=jsonObject!!.optInt("code")
                if(code==0){
                    val data= jsonObject.optJSONArray("list")
                    Log.e(TAG,"====size=1="+data!!.length())
                    for (i in 0 until data.length()) {
                        val obj=data.optJSONObject(i)
                        val dataBean=Alarm()
                        /**
                         * fid :
                         * create_time : 1735265916000
                         * alarm : 105
                         * lock_aid : e131d4fccfb3151f60977b0f1c08657c
                         * pid :
                         * time : 1735265916000
                         * category : 0
                         * lock_id : bda36ffe0919fd7624d801e0e131d4fc
                         */
                        dataBean.fid=obj.optString("fid")
                        dataBean.pid=obj.optString("pid")
                        dataBean.lock_aid=obj.optString("lock_aid")
                        dataBean.alarm=obj.optInt("alarm")
                        dataBean.category=obj.optInt("category")
                        dataBean.lock_id=obj.optString("lock_id")
                        dataBean.create_time=obj.optLong("create_time")
                        listData!!.add(dataBean)
                    }
                    showData()
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }

    @SuppressLint("NotifyDataSetChanged")
    private fun showData(){
        runOnUiThread(Runnable {
            for (i in 0 until listData!!.size) {
                var day = equesMytool!!.getYMD(listData!![i].create_time)
                var find = false
                for (animalAlarm in lists!!) {
                    if (day.equals(animalAlarm.day)) {
                        find = true
                    }
                }
                var animalAlarm = AnimalAlarmInfo()
                if (!find) {
                    animalAlarm.day = day
                    lists!!.add(animalAlarm)
                }
            }
            for(i in 0 until lists!!.size){
                var animalAlarm=lists!![i]
                for (k in 0 until listData!!.size) {
                    var day =equesMytool!!.getYMD(listData!![k].create_time)
                    if (day.equals(animalAlarm.day)) {
                        animalAlarm.tabE1ProAlarmMsgInfo.add(listData!![k])
                    }
                }
            }
            Log.e(TAG,"====size=="+lists.toString())
            animalPlanAdapter!!.notifyDataSetChanged()
        })
    }

    override fun CallBackItemClickListener(position: Int, voiceServiceType: Int, eventType: Int) {
        TODO("Not yet implemented")
    }

    override fun LongCallBackItemClickListener(position: Int) {
        TODO("Not yet implemented")
    }
}